package com.miplus.ccrm.core.service.crd;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.ServiceException;
import com.miplus.ccrm.core.controller.vo.credit.*;
import com.miplus.ccrm.core.mapper.AiListMapper;
import com.miplus.ccrm.core.mapper.CreditAccountMapper;
import com.miplus.ccrm.core.mapper.FiCreditcasesMapper;
import com.miplus.ccrm.core.pojo.ConCustomer;
import com.miplus.ccrm.core.pojo.CreditAccount;
import com.miplus.ccrm.core.pojo.FiCreditcases;
import com.miplus.ccrm.core.pojo.FiTask;
import com.miplus.ccrm.core.service.collect.*;
import com.miplus.ccrm.core.service.conf.SysNamesService;
import com.miplus.ccrm.core.service.cust.ConCustomerService;
import com.miplus.ccrm.core.utils.EnumFiChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FiTaskServiceCrdImpl implements FiTaskServiceCrd {
    @Resource
    private FiCreditcasesMapper fiCreditcasesMapper;
    @Resource
    private CreditAccountMapper creditAccountMapper;
    @Resource
    private SysNamesService sysNamesService;
    @Resource
    private AiListMapper aiListMapper;
    @Resource
    private ConCustomerService conCustomerService;
    @Resource
    private FiImportHistService fiImportHistService;
    @Resource
    private CreditCardService creditCardService;
    @Resource
    private FiTaskService fiTaskService;

    @Override
    public CrdCmdResVo crdCardFrozen(String $usrid, CrdFrozenReqVo paras)
    { //账户管制
        String clid=paras.getClid();
        if(JPubUtils.IsEmpty(clid)){
            clid="SYS_CARDFRZ";
        }
        Integer channel=paras.getChannel();
        if(JPubUtils.IsEmpty(channel)){
            channel= EnumFiChannel.Frozen.value;
        }
        //卡号客户端是加密的
        FiCreditcases creditcases=fiCreditcasesMapper.selectById(paras.getFicaseid());
        CreditAccount account=creditAccountMapper.selectOne(
                new QueryWrapper<CreditAccount>().eq("acct",creditcases.getCreditAcct())
        );
        String cardno=account.getCrdtCardRepeNo();
        String opt=sysNamesService.getNamesDsc("CREDIT.FROZEN.OPT",paras.getCrdopt());
        CrdCmdResVo crdCmdResVo=CrdCommand.crdCardFrozen(
                cardno,paras.getCrdopt(),paras.getCrdsts(),paras.getCrdorg()
        );

        fiTaskService.addTask($usrid,clid,paras.getFicaseid(),channel,
                crdCmdResVo.getRespCode(),
                opt+"("+paras.getCrdsts()+"):"+crdCmdResVo.getRespCodeDesc()
        );

        return crdCmdResVo;
    }

    //未使用，使用的是划扣申请类
    @Override
    public CrdCmdResVo crdCardDeduction(String $usrid, CrdDeduReqVo paras)
    { //卡划扣
        String clid=paras.getClid();
        if(JPubUtils.IsEmpty(clid)){
            clid="SYS_CARDDED";
        }
        Integer channel=paras.getChannel();
        if(JPubUtils.IsEmpty(channel)){
            channel=EnumFiChannel.Deduction.value;
        }
        //需要取，传的cardno参数是加密带星的
        FiCreditcases fi=fiCreditcasesMapper.selectById(paras.getFicaseid());
        ConCustomer cu=conCustomerService.getById(fi.getCustomernumber());
        String cardno=paras.getCardno();
        if(cardno.indexOf("*")>=0) {//如果不带*，直接使用，2024-06-06
            cardno=cu.getDebitcardno();
        }
        String crdcardno=creditCardService.getAccOpenLastCardNo(fi.getCreditAcct());
        CrdCmdResVo crdCmdResVo=CrdCommand.crdCarDeduction(cardno,crdcardno,paras.getAmount());

        fiTaskService.addTask($usrid,clid,paras.getFicaseid(),channel,
                crdCmdResVo.getRespCode(),"划扣金额："+paras.getAmount().toString()
        );

        return crdCmdResVo;
    }

    @Override
    public CmdResVo sendAiList(String $usrid, AiListSendVo paras)
    {
        IPage<AiListResVo> resVoIPage=null;
        String tempid=paras.getTempid();
        SimpleDateFormat sdf=new SimpleDateFormat("yyMMddHHmmssSSS");
        String batchid = "A"+sdf.format(new Date());
        if(JPubUtils.IsEqual(tempid,"ailist-ys")){
            resVoIPage=aiListMapper.quyAiListYs(new Page<>(1, 10000));
        }
        else if(JPubUtils.IsEqual(tempid,"ailist-mt")) {
            resVoIPage=aiListMapper.quyAiListMt(new Page<>(1, 10000));
        }
        else if(JPubUtils.IsEqual(tempid,"ailist-car")) {
            resVoIPage=aiListMapper.quyAiListCar(new Page<>(1, 10000));
        }
        else{
            throw new ServiceException(EnumRCode.ArgErr.value, EnumRCode.ArgErr.name);
        }

        log.info("sendAiList:batchid={},Count={}",batchid,resVoIPage.getTotal());
        int okcount=(int)resVoIPage.getTotal();

        int[] pos=new int[1];
        resVoIPage.convert(u->{
            String dataid=batchid+"."+String.format("%d",pos[0]++);
            if(JPubUtils.IsEqual(tempid,"ailist-ys")) {
                dataid=dataid+"ys";
            }
            u.setDataId(dataid);
            return u;
        });

        List<AiListResVo> collect = resVoIPage.getRecords();
        HttpCommand.SendAiList(tempid,collect);

        if(okcount>0){
            fiImportHistService.AddImportHist(batchid, "Ai推送:"+batchid, $usrid, tempid, null, okcount, okcount);
            for(AiListResVo listResVo : collect){
                fiTaskService.addTask($usrid, "SYS_AICALL", listResVo.getAcctNo(), EnumFiChannel.AiCall.value,
                        listResVo.getMobileNumber(),batchid, listResVo.getDataId()
                );
                if(JPubUtils.IsEqual(tempid,"ailist-ys")&&JPubUtils.IsNotEmpty(listResVo.getAcctNo2())){
                    fiTaskService.addTask($usrid, "SYS_AICALL", listResVo.getAcctNo2(), EnumFiChannel.AiCall.value,
                            listResVo.getMobileNumber(), batchid,listResVo.getDataId()
                    );
                }
            }
        }

        return new CmdResVo(okcount,batchid);
    }

    @Override
    public CmdResVo saveAiListResult(String $usrid,AiCallRetVo paras)
    {
        log.info("saveAiListResult:",paras);
        String dataId=paras.getDataId();
        FiTask fiTask=fiTaskService.selectJoinOne(FiTask.class,
                new MPJLambdaWrapper<FiTask>()
                        .ge(FiTask::getCrdt,JPubUtils.addDays(new Date(),-3))
                        .eq(FiTask::getChannel,EnumFiChannel.AiCall.value)
                        .eq(FiTask::getCticallid,dataId)
                        .eq("rownum",1)
        );
        if(fiTask==null){
            log.info("saveAiListResult:{} NoFind",dataId);
            return new CmdResVo(0,dataId);
        }

        String tkstatus="R";
        String result="SUCCESS";
        String resultdsc=paras.getCallNote();
        if(!JPubUtils.StringToBool(paras.getCallSuccess())) {
            tkstatus = "F";
            result="FAIL";
            resultdsc=paras.getFailCause()+","+resultdsc;
        }

        fiTaskService.saveTask(fiTask.getTasknumber(),$usrid,paras.getSendTimes(),result,resultdsc,paras.getPtp(),
                null,null,null,tkstatus
        );

        return new CmdResVo(1,dataId);
    }
}
